﻿using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;


public class MultiPlayManager : NetworkBehaviour
{
    public static MultiPlayManager Instance;
    [SerializeField] GameObject playerPrefab;
    bool isDespawn = false;
    
    //由于NetworkList的快照和增量同步机制，当在建立连接时调用Add，并且Add消息后到达客户端时，对应的客户端会多一条对应的数据
    public NetworkList<PlayerData> Players { get; private set; }    

    private void Awake()
    {        
        if (Instance == null)
        {
            Instance = this;
        }
        else
            Destroy(gameObject);

        Players = new NetworkList<PlayerData>();
    }
    
    public override void OnNetworkDespawn()
    {
        if (IsHost)
        {
            Players.Clear();
            Debug.Log("Host clear player list");
        }            
        Players.Dispose();
        isDespawn = true;
    }

    [Rpc(SendTo.ClientsAndHost)]
    public void SetPlayStateRpc(bool state)
    {
        GameManager.Instance.IsPlaying = state;
    }


    public void RemovePlayer(ulong id)
    {
        if (!NetworkObject.IsSpawned || isDespawn || !NetworkManager.IsListening)
        {
            Debug.Log("Cannot remove player: MultiPlayManager is not properly initialized.");
            return;
        }
                    
        for (int i = Players.Count-1; i>=0; i--)
        {
            if (Players[i].id == id)
            {                                
                Players.RemoveAt(i);
                Debug.Log($"Client {id} exit connected");
                break;
            }
        }
    }

    public void GeneratePlayer(Transform spawnTF)
    {        
        foreach (var player in Players)
        {
            var obj = Instantiate(playerPrefab);
            var netObj=obj.GetComponent<NetworkObject>();
            netObj.SpawnAsPlayerObject(player.id,true);
            netObj.TrySetParent(spawnTF);
        }
    }
}